import { createStore } from 'vuex'
import { UserInfoType } from '@/api/auth.type'
import { signout } from '@/api/auth'
import { ElLoading } from 'element-plus'

import router from '@/router/'

const store = createStore({
  state: {
    count: 0,
    token: localStorage.getItem('token') || '',
    isCollapse: false,
    userInfo: JSON.parse(
      localStorage.getItem('userInfo') || '{}'
    ) as UserInfoType,
  },
  mutations: {
    increment(state) {
      state.count++
    },
    setToken(state, token: string) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setUserInfo(state, userInfo: UserInfoType) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    toggleNav(state) {
      state.isCollapse = !state.isCollapse
    },
  },
  actions: {
    signOut({ commit }) {
      const loadingInstance = ElLoading.service({ fullscreen: true })
      signout().finally(() => {
        loadingInstance.close()

        commit('setToken', '')
        commit('setUserInfo', {} as UserInfoType)

        router.push({
          path: '/signin',
          query: { redirect: router.currentRoute.value.path },
        })
      })
    },
  },
})

export default store
